using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using WMS.Api.Application.Commands;
using WMS.Common;

namespace WMS.Api.Controllers
{
    /// <summary>
    /// 产品控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [AllowAnonymous]
    public class ProductsController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<ProductsController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者</param>
        /// <param name="logger">日志</param>
        public ProductsController(IMediator mediator, ILogger<ProductsController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 获取产品列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页大小</param>
        /// <param name="productName">产品名称</param>
        /// <param name="sku">SKU编码</param>
        /// <param name="productTypeId">产品类型ID</param>
        /// <returns>产品列表</returns>
        [HttpGet]
        public async Task<ApiResult<PagingResult<List<ProductDto>>>> GetProductList(
            int pageIndex = 1, 
            int pageSize = 10, 
            string? productName = null, 
            string? sku = null, 
            int? productTypeId = null)
        {
            try
            {
                var command = new GetProductListCommand
                {
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    ProductName = productName,
                    SKU = sku,
                    ProductTypeId = productTypeId
                };

                return await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取产品列表失败");
                return new ApiResult<PagingResult<List<ProductDto>>>("获取产品列表失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 获取产品详情
        /// </summary>
        /// <param name="id">产品ID</param>
        /// <returns>产品详情</returns>
        [HttpGet]
        public async Task<ApiResult<ProductDto>> GetProductById(int id)
        {
            try
            {
                var command = new GetProductByIdCommand { Id = id };
                return await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取产品详情失败");
                return new ApiResult<ProductDto>("获取产品详情失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 创建产品
        /// </summary>
        /// <param name="product">产品信息</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public async Task<ApiResult<int>> CreateProduct([FromBody] ProductDto product)
        {
            try
            {
                var command = new CreateProductCommand { Product = product };
                return await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建产品失败");
                return new ApiResult<int>("创建产品失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 更新产品
        /// </summary>
        /// <param name="product">产品信息</param>
        /// <returns>操作结果</returns>
        [HttpPut]
        public async Task<ApiResult<int>> UpdateProduct([FromBody] ProductDto product)
        {
            try
            {
                var command = new UpdateProductCommand { Product = product };
                return await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新产品失败");
                return new ApiResult<int>("更新产品失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 删除产品
        /// </summary>
        /// <param name="id">产品ID</param>
        /// <returns>操作结果</returns>
        [HttpDelete]
        public async Task<ApiResult<int>> DeleteProduct(int id)
        {
            try
            {
                var command = new DeleteProductCommand { Id = id };
                return await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除产品失败");
                return new ApiResult<int>("删除产品失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 批量删除产品
        /// </summary>
        /// <param name="ids">产品ID列表</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public async Task<ApiResult<int>> BatchDeleteProduct([FromBody] List<int> ids)
        {
            try
            {
                var command = new BatchDeleteProductCommand { Ids = ids };
                return await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除产品失败");
                return new ApiResult<int>("批量删除产品失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 导入产品
        /// </summary>
        /// <param name="file">Excel文件</param>
        /// <returns>导入结果</returns>
        [HttpPost]
        public async Task<ApiResult<ImportResult>> ImportProduct(IFormFile file)
        {
            try
            {
                var command = new ImportProductCommand { File = file };
                return await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导入产品失败");
                return new ApiResult<ImportResult>("导入产品失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 导出产品
        /// </summary>
        /// <param name="productName">产品名称</param>
        /// <param name="sku">SKU编码</param>
        /// <param name="productTypeId">产品类型ID</param>
        /// <returns>Excel文件</returns>
        [HttpGet]
        public async Task<IActionResult> ExportProduct(
            string? productName = null, 
            string? sku = null, 
            int? productTypeId = null)
        {
            try
            {
                var command = new ExportProductCommand
                {
                    ProductName = productName,
                    SKU = sku,
                    ProductTypeId = productTypeId
                };

                var result = await _mediator.Send(command);

                if (result.isSuc && result.data != null)
                {
                    return File(
                        result.data,
                        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                        $"产品列表_{DateTime.Now:yyyyMMddHHmmss}.xlsx");
                }

                return BadRequest(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出产品失败");
                return BadRequest(new ApiResult<object>("导出产品失败：" + ex.Message));
            }
        }

        /// <summary>
        /// 上传产品图片
        /// </summary>
        /// <param name="file">图片文件</param>
        /// <returns>图片URL</returns>
        [HttpPost]
        public async Task<ApiResult<string>> UploadImage(IFormFile file)
        {
            try
            {
                var command = new ProductUploadImageCommand { File = file };
                return await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "上传产品图片失败");
                return new ApiResult<string>("上传产品图片失败：" + ex.Message);
            }
        }
    }
} 